<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\logic\HandlerApi;
use app\common\model\ad\Click;
use think\Db;

/**
 * 首页接口
 */
class Ads extends Api
{
    protected $noNeedLogin = ['search', 'first', 'start', 'adclick', 'getHrefLimit'];
    protected $noNeedRight = ['*'];


    /**
     * 搜索接口
     */
    public function search() {
        $page = input('page/d', 1);
        $keyword = input('keyword/s', '');
        if (!$keyword) {
            $keyword = config('site.search_default');
        }
        $api = new HandlerApi();
        $this->success('搜索', $api->search($keyword, $page));
    }


    /**
     * 首页接口
     */
    public function first() {
        $page = input('page/d', 1);
        $api = new HandlerApi();
        $this->success('搜索', $api->first($page));
    }


    /**
     * 启动导航
     */
    public function start() {
        $api = new HandlerApi();
        $this->success('搜索', $api->start());
    }

    //屏蔽
    public function on() {
        //0标示未开启， 1标示已开启
        $type = input('on/d', 1);
        if ($type != 0 && $type != 1) {
            $this->error('参数传递错误');
        }
        $on = Db::name('pingbi')->where(['user_id' => $this->auth->id])->find();
        if ($on) {
            Db::name('pingbi')->where(['user_id'=> $this->auth->id])->setField('is_on', $type);
        } else {
            Db::name('pingbi')->insert([
                'user_id' => $this->auth->id,
                'is_on' => $type,
                'count' => rand(10, 50)
            ]);
        }

        $this->success('保存成功');
    }

    public function getOn() {
        $inc = rand(5, 50);
        Db::name('pingbi')->where(['user_id'=> $this->auth->id])->setInc('count', $inc);

        $info = Db::name('pingbi')->where(['user_id'=> $this->auth->id])->find();

        $this->success('屏蔽信息', $info);
    }

    //点击广告
    public function adclick() {
        $id = input('ad_id/d', 0);
        $from = input('from', ''); //ios  android
        if (defined('UID') && UID) {
            $type = 1; //会员
        } else {
            $type = 0; //非会员
        }
        $ad = \app\common\model\ad\Ads::get($id);
        //屏蔽错误
        if ($ad) {
            Click::create([
                'type' => $type,
                'from' => $from,
                'ad_id' => $ad['id'],
                'createtime' => time()
            ]);
        }

        $this->success('记录成功');
    }

    public function getHrefLimit() {
        $list = Db::name('ad_ip')->column('href');

        $this->success('白名单', $list);
    }

}
